const Koa = require("koa");
const fs = require('fs');
const path = require("path");

const app = new Koa();

app.use((ctx) => {
  const url = ctx.request.url;

  if (url === '/') {
    // 加载html
    ctx.body = fs.readFileSync("./index.html", "utf-8");
  } else if (url.endsWith(".js")) {
    // 找到对应路径 去加载 然后给到浏览器
    const p = path.resolve(__dirname, url.slice(1));
    ctx.type = "text/javascript";
    // 做一个标识
    const source = fs.readFileSync(p, "utf-8");
    ctx.body = rewriteImport(source);
  } else if (url.startsWith("/@modules")) {
    // 第三方库  加载包
    // 应该从node_modules 里面去查找
    const moduleName = url.replace("/@modules", "");
    // url -> vue
    const prefix = __dirname + "/node_modules" + moduleName;
    // package.json
    const module = require(prefix + "/package.json").module;

    const code = fs.readFileSync(path.resolve(prefix, module), "utf-8");
    ctx.type = "text/javascript";
    ctx.body = rewriteImport(code);
  }
})

function rewriteImport(source) {
  return source.replace(/(from\s+['"])(?![\.\/])/g, "$1/@modules/")
    .replace(/process\.env\.NODE_ENV/g, "'development'");
}

app.listen(8080, (ctx) => {
  console.log("open server http://localhost:8080");
});